<script>
import axios from "axios";

export default {
  name: "qk",
  data() {
    return {
      state: {
        page: 1,
        size: 5,
        books: [],
        types: [],
        total: 0,
        dialogFormVisible: false,
        dialogAddFormVisible: false,
        form: {},
        addFrom: {},
        formLabelWidth: '120px',
        fileList: [],
        search: ''
      },
      rules: {
        name: [
          {required: true, message: '请输入期刊名称', trigger: 'blur'},
          {max: 30, message: '最多 30 个字符', trigger: 'blur'}
        ],
        periods: [
          {required: true, message: '请选择期刊每年发行期数', trigger: 'change'}
        ],
        createTime: [
          {required: true, message: '请选择发行日期', trigger: 'change'}
        ],
        type: [
          {required: true, message: '请选择期刊类型', trigger: 'change'}
        ],
        num: [
          {required: true, message: '请输入库存', trigger: 'blur'},
          {type: 'number', message: '库存是数字', trigger: 'blur', transform: (value) => Number(value)}
        ],
        price: [
          {required: true, message: '请输入单价', trigger: 'blur'},
          {type: 'number', message: '单价是数字', trigger: 'blur', transform: (value) => Number(value)}
        ],
      }
    }
  },
  methods: {
    getQk() {
      this.$api.book.getBooks(
          this.state.page,
          this.state.size,
          '',
          this.state.search
      ).then((res) => {
        var data = res.data;
        if (data.success) {
          this.state.books = data.content.records;
          this.state.total = data.content.total
        } else {
          this.$message.error('服务器返回失败');
        }
      }).catch((resp) => {
        this.$message.error('服务器访问失败' + resp);
      });
    },
    handleEdit(row) {
      this.state.form = JSON.parse(JSON.stringify(row))
      this.state.dialogFormVisible = true
    },
    handleDelete(row) {
      this.$api.book.deleteBook(row.id, row.coverAddress).then((res) => {
        var data = res.data;
        if (data.success) {
          this.$message.success('删除成功');
          this.state.page = 1;
          this.getQk();
        } else {
          this.$message.error('服务器返回失败');
        }
      }).catch((resp) => {
        this.$message.error('服务器访问失败' + resp);
      });
    },
    handleCurrentChange() {
      this.getQk();
    },
    align() {
      return "text-align:center"
    },
    addFileSuccess(res) {
      this.state.addFrom.coverAddress = 'http://localhost:8088/img/' + res.message
    },
    fileSuccess(res) {
      this.state.form.coverAddress = 'http://localhost:8088/img/' + res.message
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1;
      let size = true;
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      if (this.state.fileList.length > 0) {
        size = false
        this.$message.error('封面只能上传1张');
      }
      return isLt2M && size;
    },
    //新增
    submitAddBook(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$api.book.addBook(this.state.addFrom).then((res) => {
            var data = res.data;
            if (data.success) {
              this.$message.success('新增成功');
              this.state.dialogAddFormVisible = false
              this.getQk()
            } else {
              this.$message.error(res.data.message);
            }
          }).catch((resp) => {
            this.$message.error('服务器访问失败' + resp);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //修改
    submitEditBook(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          delete this.state.form["pt"]
          this.$api.book.updateBook(this.state.form).then((res) => {
            var data = res.data;
            if (data.success) {
              this.$message.success('修改成功');
              this.state.dialogFormVisible = false
              this.getQk()
            } else {
              this.$message.error(res.data.message);
            }
          }).catch((resp) => {
            this.$message.error('服务器访问失败' + resp);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //取消
    cancelEdit(formName) {
      this.state.dialogFormVisible = false
      this.state.dialogAddFormVisible = false
      console.log(this.state.addFrom)
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.getQk();
    this.$api.bookType.getBookType().then((res) => {
      var data = res.data;
      if (data.success) {
        this.state.types = data.content;
      } else {
        this.$message.error('服务器返回失败');
      }
    }).catch((resp) => {
      this.$message.error('服务器访问失败' + resp);
    })
  }
}
</script>

<template>
  <div>
    <el-button type="primary" @click="state.dialogAddFormVisible=true">新增</el-button>
    <div style="display: inline-flex;margin: 0 10px 10px;">
      <el-input
          v-model="state.search"
          placeholder="输入期刊名称"
          prefix-icon="el-icon-search"
          style="width: 300px;margin-right: 10px"
          clearable
          @clear="getQk"
          @keydown.enter.native="getQk"></el-input>
      <el-button
          icon="el-icon-search"
          type="primary"
          @click="getQk">
        搜索
      </el-button>
    </div>
    <el-table
        :data="state.books"
        border
        :cell-style="align"
        style="width: 100%">
      <el-table-column
          label="封面"
          width="100"
          align="center">
        <template slot-scope="scope">
          <img width="50px" :src="scope.row.coverAddress " alt=""/>
        </template>
      </el-table-column>
      <el-table-column
          prop="name"
          align="center"
          label="名称">
      </el-table-column>
      <el-table-column
          prop="pt.name"
          align="center"
          label="类型">
      </el-table-column>
      <el-table-column
          label="发行时间"
          align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="期数（年）">
        <template slot-scope="scope">
          <span>{{ scope.row.periods }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="单价（元）">
        <template slot-scope="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="库存">
        <template slot-scope="scope">
          <span>{{ scope.row.num }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="销量">
        <template slot-scope="scope">
          <span>{{ scope.row.salesNum }}</span>
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="描述">
        <template slot-scope="scope">
          <span>{{ scope.row.intro }}</span>
        </template>
      </el-table-column>
      <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="150">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          &nbsp
          <el-popconfirm title="确定删除这条数据吗？"
                         confirm-button-text="确定"
                         cancel-button-text="取消"
                         @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button size="small" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="width: 99%;display: flex">
      <div style="margin: 10px auto;">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="state.page"
            :page-size="state.size"
            layout="total, prev, pager, next"
            :total="state.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增qk -->
    <el-dialog title="新增期刊" width="500px" :visible.sync="state.dialogAddFormVisible">
      <el-form :model="state.addFrom" :rules="rules" ref="addForm" :label-width="state.formLabelWidth">
        <el-form-item label="期刊名称" prop="name">
          <el-input style="width: 218px;" v-model="state.addFrom.name" autocomplete="off" placeholder="请输入期刊名称"/>
        </el-form-item>
        <el-form-item label="期刊类型" prop="type">
          <el-select v-model="state.addFrom.type" placeholder="请选择类型">
            <el-option v-for="(item,index) in state.types" :key="index" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="期数(年)" prop="periods">
          <el-select v-model="state.addFrom.periods" placeholder="请选择期数">
            <el-option label="12" value="12"></el-option>
            <el-option label="24" value="24"></el-option>
            <el-option label="36" value="36"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              v-model="state.addFrom.createTime"
              align="right"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input style="width: 218px;" v-model="state.addFrom.price" autocomplete="off" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="期刊库存" prop="num">
          <el-input style="width: 218px;" v-model="state.addFrom.num" autocomplete="off" placeholder="请输入库存"/>
        </el-form-item>
        <el-form-item label="期刊简介">
          <el-input type="textarea" style="width: 218px;" v-model="state.addFrom.intro" autocomplete="off"
                    placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="图片" :label-width="state.formLabelWidth">
          <el-upload
              class="upload-demo"
              action="http://localhost:8088/ty-book/uploadFile"
              :file-list="state.fileList"
              :on-success="addFileSuccess"
              :onbeforeinput="beforeAvatarUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">图片不超过1Mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitAddBook('addForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑qk -->
    <el-dialog title="编辑期刊" width="500px" :visible.sync="state.dialogFormVisible">
      <el-form :model="state.form" :rules="rules" ref="editForm" :label-width="state.formLabelWidth">
        <el-form-item label="期刊名称" prop="name">
          <el-input style="width: 218px;" v-model="state.form.name" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="期刊类型" prop="type">
          <el-select v-model="state.form.type" placeholder="请选择类型">
            <el-option v-for="(item,index) in state.types" :key="index" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="期数(年)" prop="periods">
          <el-select v-model="state.form.periods" placeholder="请选择期数">
            <el-option label="12" value="12"></el-option>
            <el-option label="24" value="24"></el-option>
            <el-option label="36" value="36"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
              v-model="state.form.createTime"
              align="right"
              type="date"
              placeholder="选择日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input style="width: 218px;" v-model="state.form.price" autocomplete="off" placeholder="请输入单价"/>
        </el-form-item>
        <el-form-item label="期刊库存" prop="num">
          <el-input style="width: 218px;" v-model="state.form.num" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="期刊简介">
          <el-input type="textarea" style="width: 218px;" v-model="state.form.intro" autocomplete="off"
                    placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8088/ty-book/uploadFile"
              :file-list="state.fileList"
              :on-success="fileSuccess"
              :onbeforeinput="beforeAvatarUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件不超过1Mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitEditBook('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style scoped>
</style>